package com.org.controller.mail;

import cn.hutool.core.util.RandomUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author Rainy-Heights
 * @version 1.0
 * @Date 2023/3/23 21:09
 */
@Controller
//注意使用rest风格就不会跳转页面了
@RequestMapping("/mail")
public class MailController {
    @Resource
    private JavaMailSender mailSender;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/success")
    public String success(){
        return "/success";
    }

    @RequestMapping("/code")
    //先获取邮箱参数试试
    public String getCode(HttpServletRequest request){
        int range= Math.toIntExact(RandomUtil.randomLong(100000, 999999));//限定为6位数的验证码
        stringRedisTemplate.opsForValue().set("code", String.valueOf(range),5,TimeUnit.MINUTES);//设置过期时间为5分钟

        String destination=request.getParameter("email");

        //下面 发送邮件
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        mailMessage.setSubject("【人间词话验证码】");
        Date date=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mailMessage.setText((dateFormat.format(date))+","+"您的登录验证码为："+range+"此条验证码将在5分钟内过期");

        mailMessage.setTo(destination);//前端获取发送的邮件对象参数，实现发送的定向操作

//        mailMessage.setTo("rainymix@yeah.net");
        mailMessage.setFrom("rainymix@yeah.net");//必须要一致，当前的发送方

        try {
            mailSender.send(mailMessage);
            System.out.println("An auth_code has been sent");
//            if (true) throw new RuntimeException();
            return "redirect:/mail/success";
        }catch (Exception e){
            return "/error/pages-500";
        }

    }
}
